import { AsyncStorage } from 'react-native';
import { kAuthorization, kContentType } from "../constant";
import Request from "../utils/Request";
const moment = require('moment');
const STORAGE_KEY = "STORAGE_KEY_chat";
export default {
    namespace: 'chat',
    state: {
        friendList: [],
        loading: false,
        messageList: null,
        socket: null,
        searchUsers: null,
    },
    reducers: {
        save(state, { payload }) {
            return Object.assign({}, state, payload);
        }
    },
    effects: {
        *saveToStorage({ payload }, { call }) {
            yield call(AsyncStorage.setItem, STORAGE_KEY, JSON.stringify(payload));
        },
        *restoreFromStorage({ payload }, { call, put, select }) {
            const data = yield call(AsyncStorage.getItem, STORAGE_KEY);
            yield put({
                type: 'save',
                payload: Object.assign({}, JSON.parse(data))
            });
        },
        *clear({ payload }, { put }) {
        },
        *fetchFriends({ payload }, { call, put, select }) {
            const auth = yield select(state => state.auth);
            if (!payload)
                payload = { id: auth.userInfo.id };
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            yield put({ type: 'save', payload: { loading: true } });
            const friendList = yield call(Request.get, Request.getApi().chatList, payload);
            if (friendList && Array.isArray(friendList)) {
                yield put({
                    type: 'save',
                    payload: { friendList, loading: false }
                });
            }
            else {
                yield put({ type: 'save', payload: { loading: false } });
            }
        },
        *fetchMessageList({ payload }, { call, put, select }) {
            const auth = yield select(state => state.auth);
            let chat = yield select(state => state.chat);
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            payload['sender'] = auth.userInfo.account;
            yield put({ type: 'save', payload: { loading: true } });
            const result = yield call(Request.get, Request.getApi().messageList, payload);
            if (result) {
                if (!chat.messageList)
                    chat.messageList = { content: [] };
                const resultList = result.content.map((message) => (Object.assign({}, message, { _id: message.id, text: message.content, createdAt: moment(message.date).toDate(), user: {
                        _id: message.sender,
                        name: message.nickname,
                        avatar: message.avatar ? message.avatar : '',
                    } })));
                chat.messageList.first = result.first;
                chat.messageList.last = result.last;
                chat.messageList.number = result.number;
                chat.messageList.numberOfElements = result.numberOfElements;
                chat.messageList.size = result.size;
                chat.messageList.totalElements = result.totalElements;
                chat.messageList.totalPages = result.totalElements;
                if (payload.loadmore) {
                    const content = chat.messageList.content;
                    chat.messageList.content = content.concat(resultList);
                }
                else {
                    chat.messageList.content = resultList;
                }
                yield put({
                    type: 'save',
                    payload: Object.assign({}, chat, { loading: false })
                });
            }
            else {
                yield put({ type: 'save', payload: { messageList: null, loading: false } });
            }
        },
        *clearList({ payload }, { put, select }) {
            const chat = yield select(state => state.chat);
            chat.messageList = null;
            yield put({
                type: "save",
                payload: Object.assign({}, chat)
            });
        },
        *sendMessage({ payload }, { call, put, select }) {
            let chat = yield select(state => state.chat);
            let content = [];
            content = Object.assign(content, chat.messageList.content);
            content.unshift(payload.message);
            chat.messageList.content = content;
            yield put({
                type: 'save',
                payload: Object.assign({}, chat)
            });
            if (payload.save) {
                yield put({
                    type: 'saveMessage',
                    payload: payload.origin
                });
            }
        },
        *saveMessage({ payload }, { call, select }) {
            const auth = yield select(state => state.auth);
            let params = { params: payload };
            params[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            params[kContentType] = 'application/json';
            yield call(Request.post, Request.getApi().saveMessage, params);
        },
        *saveSocketInstant({ payload }, { put }) {
            yield put({ type: 'save', payload });
        },
        *contact({ payload }, { call, select }) {
            let params = { params: Object.assign({}, payload) };
            const auth = yield select(state => state.auth);
            params[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            params[kContentType] = 'application/json';
            yield call(Request.post, Request.getApi().contact, params);
        },
        *searchUser({ payload }, { call, put, select }) {
            if (!payload)
                payload = {};
            const auth = yield select(state => state.auth);
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            const data = yield call(Request.get, Request.getApi().searchUser, payload);
            if (data) {
                yield put({
                    type: 'save',
                    payload: { searchUsers: data }
                });
            }
        },
    },
    subscriptions: {
        setup({ dispatch }) {
        }
    },
};
